package com.key;

import com.key.center.KeyCenterBuildFactory;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Author dzl
 * @Date 2021/11/15 9:49 上午
 * 安全工，用于key的加解密
 */
public class SafeUtil {
    /**
     * 加密算法
     *
     * @param input 原文
     * @return 密文
     * @throws Exception /
     */
    public static String encrypt(String input) throws Exception {
        String key = KeyCenterBuildFactory.KEY_CENTER.SecretKey();
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 解密
     *
     * @param input 密文
     * @return 原文
     * @throws Exception /
     */
    public static String decrypt(String input) throws Exception {
        String key = KeyCenterBuildFactory.KEY_CENTER.SecretKey();
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(input));
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
